package com.recruit.server.service.impl;

import com.recruit.server.common.HeaderInfo;
import com.recruit.server.common.OrderStatusEnum;
import com.recruit.server.common.utils.BigDecimalUtil;
import com.recruit.server.dao.CartMapper;
import com.recruit.server.dao.OrderItemMapper;
import com.recruit.server.dao.OrderMapper;
import com.recruit.server.dao.ProductMapper;
import com.recruit.server.entity.pojo.Cart;
import com.recruit.server.entity.pojo.Order;
import com.recruit.server.entity.pojo.OrderItem;
import com.recruit.server.entity.pojo.Product;
import com.recruit.server.request.order.AddOrderRequest;
import com.recruit.server.request.order.ListOrderRequest;
import com.recruit.server.request.order.UpdateOrderRequest;
import com.recruit.server.response.order.AddOrderResponse;
import com.recruit.server.response.order.ListOrderResponse;
import com.recruit.server.response.order.UpdateOrderResponse;
import com.recruit.server.response.product.ProductDetailResponse;
import com.recruit.server.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Slf4j
@Service
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public ListOrderResponse list(ListOrderRequest request, HeaderInfo headerInfo) {
        ListOrderResponse response = new ListOrderResponse();
        try {
            List<Order> orderList = orderMapper.selectByUserId(headerInfo.getUserId());
            response.setOrderList(orderList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setCodeAndMessage(-1, e.getMessage());
        }
        return response;
    }

    @Override
    public AddOrderResponse add(AddOrderRequest request, HeaderInfo headerInfo) {
        AddOrderResponse response = new AddOrderResponse();
        try {
            // select carts from mysql db by userId
            List<Cart> cartList = cartMapper.selectCheckedCartByUserId(headerInfo.getUserId());
            List<OrderItem> orderItemList = new ArrayList<>();
            for (Cart cart : cartList) {
                // select product from mysql db by productId
                Product product = productMapper.selectByPrimaryKey(cart.getProductId());
                //create order info
                OrderItem orderItem = new OrderItem();
                orderItem.setUserId(headerInfo.getUserId());
                orderItem.setProductId(product.getId());
                orderItem.setProductName(product.getName());
                orderItem.setProductImage(product.getMainImage());
                orderItem.setCurrentUnitPrice(product.getPrice());
                orderItem.setQuantity(cart.getQuantity());
                orderItem.setTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(), cart.getQuantity()));
                orderItemList.add(orderItem);
            }
            // calculate order monery
            BigDecimal payment = this.getOrderTotalPrice(orderItemList);
            // 创建订单
            Order order = this.assembleOrder(headerInfo.getUserId(), request.getShippingId(), payment);
            if (order == null) {
                response.setCodeAndMessage(-1, "generate order error");
                return response;
            }
            for (OrderItem orderItem : orderItemList) {
                orderItem.setOrderNo(order.getOrderNo());
            }
            // 插入订单详情
            orderItemMapper.batchInsert(orderItemList);
            // 清空下购物车记录
            this.cleanCart(cartList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setCodeAndMessage(-1, e.getMessage());
        }
        return response;
    }

    private void cleanCart(List<Cart> cartList) {
        for (Cart cart : cartList) {
            // delete cart record from mysql
            cartMapper.deleteByPrimaryKey(cart.getId());
        }
    }

    private Order assembleOrder(Integer userId, Integer shippingId, BigDecimal payment) {
        Order order = new Order();
        // 生成订单号
        long orderNo = this.generateOrderNo();
        order.setOrderNo(orderNo);
        order.setStatus(OrderStatusEnum.NO_PAY.getCode());
        order.setPostage(0);
        order.setPayment(payment);
        order.setUserId(userId);
        order.setShippingId(shippingId);
        //insert order info to mysql
        int rowCount = orderMapper.insert(order);
        if (rowCount > 0) {
            return order;
        }
        return null;
    }

    private long generateOrderNo() {
        long currentTime = System.currentTimeMillis();
        return currentTime + new Random().nextInt(100);
    }

    // 计算订单金额
    private BigDecimal getOrderTotalPrice(List<OrderItem> orderItemList) {
        BigDecimal payment = BigDecimal.ZERO;
        for (OrderItem orderItem : orderItemList) {
            payment = BigDecimalUtil.add(payment.doubleValue(), orderItem.getTotalPrice().doubleValue());
        }
        return payment;
    }
}
